<?php

	/**
	 * 
	 * Controller principal da aplicacao INDEX
	 * @author Jeferson Rodrigues
	 * @since 20/02/2012
	 *
	 */
	class IndexController extends Zend_Controller_Action
	{
		/*
		 * Atibutos da classe
		 */
		private $_objModelDbTableAlbums;
	    private $_objFormAlbum;
		
	    /**
	     * Inicializa os objetos necessarios para os outros metodos
	     * @see Zend_Controller_Action::init()
	     * @return VOID
	     */
	    public function init()
	    {
	    	$this->_objModelDbTableAlbums	= new Application_Model_DbTable_Albums();
	    	$this->_objFormAlbum			= new Application_Form_Album();
	    }
	
	    /**
	     * Action da index
	     * @return VOID
	     */
	    public function indexAction()
	    {
			$this->view->albums = $this->_objModelDbTableAlbums->fetchAll();
	    }
	
	    /**
	     * Action do novo formulario
	     * @return VOID
	     */
	    public function addAction()
	    {
			$this->_objFormAlbum->submit->setLabel( "Add" );
			$this->view->form = $this->_objFormAlbum;
			if ( $this->getRequest()->isPost() )
			{
				$formData = $this->getRequest()->getPost();
				if ( $this->_objFormAlbum->isValid( $formData ) )
				{
					$artist	= $this->_objFormAlbum->getValue( "artist" );
					$title	= $this->_objFormAlbum->getValue( "title" );
					$this->_objModelDbTableAlbums->addAlbum( $artist , $title );
					$this->_helper->redirector( "index" );
				}
				else $this->_objFormAlbum->populate( $formData );
			}
	    }
	
	    /**
	     * Action do formulario de edicao
	     * @return
	     */
	    public function editAction()
	    {
			$this->_objFormAlbum->submit->setLabel( "Save" );
			$this->view->form = $this->_objFormAlbum;
			if ( $this->getRequest()->isPost() )
			{
				$formData = $this->getRequest()->getPost();
				if ( $this->_objFormAlbum->isValid( $formData ) )
				{
					$id		= (int)$this->_objFormAlbum->getValue( "id" );
					$artist	= $this->_objFormAlbum->getValue( "artist" );
					$title	= $this->_objFormAlbum->getValue( "title" );
					$this->_objModelDbTableAlbums->updateAlbum( $id , $artist , $title );
					$this->_helper->redirector( "index" );
				}
				else $this->_objFormAlbum->populate( $formData );
			}
			else
			{
				$id = $this->_getParam( "id" , 0 );
				if ( $id > 0 ) $this->_objFormAlbum->populate( $this->_objModelDbTableAlbums->getAlbum( $id ) );
			}
	    }
	
	    /**
	     * Action para exclusao
	     * @return VOID
	     */
	    public function deleteAction()
	    {
		    if ( $this->getRequest()->isPost() )
		    {
				$del = $this->getRequest()->getPost( "del" );
				if ( $del == "Yes" )
				{
					$id = $this->getRequest()->getPost( "id" );
					$this->_objModelDbTableAlbums->deleteAlbum( $id );
				}
				$this->_helper->redirector( "index" );
			}
			else
			{
				$id = $this->_getParam( "id" , 0 );
				$this->view->album = $this->_objModelDbTableAlbums->getAlbum( $id );
			}
	    }
	}